<?php

namespace WeChat\Controller;

use Common\Model\MemberModel;
//购物车控制器

class CartController extends BaseController {

    protected function _initialize() {

        parent::_initialize();
    }

    /*
     * 购物车
     */

    public function index() {

        $cart_price = $this->cart->getPrice();  //购物车商品价格总计

        $cart_list = $this->cart->getCart();  //购物车商品数据

        $this->assign("cart_list", $cart_list);
        $this->assign("cart_price", $cart_price);
        $this->display();
    }

    /*
     * 添加商品到购物车
     * 
     * &nojump 加入购物车（false）不跳转 /立即购买(true)跳转
     */

    public function add($id, $ajax = false, $nojump = false) {

        $goods_count = I("get.gcount", 1);

        $status = '';

        if ($goods_count) {

            $status = $this->cart->addGoods($id, $goods_count);
        }

        if ($status['status']) {

            if ($nojump) {

                redirect(U("index"));
            } else {

                $this->success($status, U("index"), $ajax);
            }
        } else {

            $this->error($status, "", $ajax);
        }
    }

    /*
     * 删除购物车商品
     */

    public function del($id, $ajax = false, $nojump = false) {

        $status = $this->cart->delItem($id);

        if ($status) {

            if ($nojump) {

                redirect(U("index"));
            } else {

                $this->success("成功删除商品", U("index"), $ajax);
            }
        } else {

            $this->error("删除商品失败", "", $ajax);
        }
    }

    /*
     * 更改购物车商品
     */

    public function modify($id, $ajax = false, $nojump = false) {

        $goods_count = I("get.gcount");

        $status = FALSE;

        if ($goods_count) {

            $status = $this->cart->modNum($id, $goods_count);

            $cart['price'] = $this->cart->getPrice();
            $cart['num'] = $this->cart->getNum();
        } else {

            $status = $this->cart->modNum($id);
        }


        if ($status) {

            if ($nojump) {

                redirect(U("index"));
            } else {

                $this->success($cart, U("index"), $ajax);
            }
        } else {

            $this->error("修改商品数量失败", "", $ajax);
        }
    }

    /*
     * 清空购物车
     */

    public function clear() {

        $this->cart->clear();

        $this->success("成功添加到购物车", "", TRUE);
    }

}
